package com.shanzhi.dify.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shanzhi.connection.common.HttpRequestType;
import com.shanzhi.dify.common.DifyUrlEnums;
import com.shanzhi.dify.config.DifyProperties;
import com.shanzhi.dify.service.DifyBaseService;
import com.shanzhi.dify.utils.DifyCommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriTemplate;

import java.util.Map;

/**
 * dify的基础接口：用于配置注入，输出优化等
 */
@Service
@Slf4j
public class DifyBaseServiceImpl implements DifyBaseService {

    @Autowired
    private DifyProperties difyProperties;


    @Override
    public String getRealUrl(DifyUrlEnums difyUrlEnums, Object... pathParams) {
        String baseUrl = difyProperties.getDifyUrl() + difyUrlEnums.getUrlSuffix();
        if (pathParams != null && pathParams.length > 0) {
            return new UriTemplate(baseUrl).expand(pathParams).toString();
        }
        return baseUrl;
    }

    @Override
    public String buildUrl(DifyUrlEnums urlEnum, Object... pathParams) {
        String url = getRealUrl(urlEnum, pathParams);
        log.info("请求路径：{}", url);
        return url;
    }


    /**
     * 发送Dify请求
     * @param entity
     * @param apiKey
     * @param urlEnum
     * @param httpRequestType
     * @param params
     * @param pathParams
     * @return
     */
    @Override
    public String sendDifyRequest(Object entity, String apiKey, DifyUrlEnums urlEnum, HttpRequestType httpRequestType, Map<String, Object> params, Object... pathParams) {
        // 参数预处理
        apiKey = resolveApiKey(apiKey);
        String url = buildUrl(urlEnum, pathParams);

        // 处理不同的请求
        switch (httpRequestType) {
            case POST:
                return DifyCommonUtils.sendDify(JSONObject.toJSONString(entity), apiKey, url, HttpRequestType.POST, null);
            case GET:
                return DifyCommonUtils.sendDify(null, apiKey, url, HttpRequestType.GET, params);
        }

        // 可以添加其他请求类型的处理
        throw new IllegalArgumentException("Unsupported HTTP request type: " + httpRequestType);
    }

    /**
     * 处理apiKey
     * 如果apiKey为空，则使用dify的默认apiKey，即知识库API Key
     * @param apiKey
     * @return
     */
    @Override
    public String resolveApiKey(String apiKey) {
        return StringUtils.hasText(apiKey) ? apiKey : difyProperties.getDatasetApiKey();
    }

}
